package com.zbkj.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.enums.EventMessageType;
import com.zbkj.common.model.bsy.BsyUser;
import com.zbkj.common.model.bsy.EventMsg;
import com.zbkj.common.request.BindBsyAccountRequest;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.common.utils.EncryptUtils;
import com.zbkj.service.dao.BsyUserDao;
import com.zbkj.service.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * 用户表 服务实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class BsyUserServiceImpl extends ServiceImpl<BsyUserDao, BsyUser> implements BsyUserService {

    private Logger logger = LoggerFactory.getLogger(BsyUserServiceImpl.class);

    @Resource
    private BsyUserDao bsyUserDao;


    /**
     * 通过贝视优业务系统调用MQ的方式注册用户
     * @param eventMessage 请求参数
     */
    @Override
    @Transactional
    public void save(EventMsg eventMessage) {
        BsyUser bsyUser = jsonToEntity(eventMessage);
        logger.info("x------------------------------------{}");
        logger.info(JSONObject.toJSONString(bsyUser));
        bsyUserDao.insert(bsyUser);
    }

    /**
     * 通过贝视优业务系统调用MQ的方式修改用户
     * @param eventMessage 请求参数
     */
    @Override
    @Transactional
    public void update(EventMsg eventMessage) {
        BsyUser bsyUser = jsonToEntity(eventMessage);
        QueryWrapper<BsyUser> queryWrapper = new QueryWrapper<BsyUser>();
        queryWrapper.eq("biz_id",bsyUser.getBizId());
        queryWrapper.eq("role_type",bsyUser.getRoleType());
        BsyUser result = bsyUserDao.selectOne(queryWrapper);
        if(result != null){
            BeanUtils.copyProperties(bsyUser,result,new String[]{"id","doctorId"});
            result.setUpdateTime(DateUtil.nowDateTime());
            bsyUserDao.updateById(result);
        }
    }

    /**
     * 查看贝视优账号是否存在
     * @param request
     * @return
     */
    @Override
    public BsyUser selectBsyAccount(BindBsyAccountRequest request) {
        QueryWrapper<BsyUser> queryWrapper = new QueryWrapper<BsyUser>();
        queryWrapper.eq("user_name",request.getUserName());
        queryWrapper.eq("password", EncryptUtils.encryptPassword(request.getPassword()));
        BsyUser bsyUser = bsyUserDao.selectOne(queryWrapper);
        return bsyUser;
    }

    @Override
    public BsyUser selectBsyUserByBizId(Long bizId) {
        QueryWrapper<BsyUser> queryWrapper = new QueryWrapper<BsyUser>();
        queryWrapper.eq("id",bizId);
        BsyUser bsyUser = bsyUserDao.selectOne(queryWrapper);
        return bsyUser;
    }

    /**
     * 消息转实体类解析字段
     * @param eventMessage
     * @return
     */
    private BsyUser jsonToEntity (EventMsg eventMessage){
        BsyUser bsyUser = null;
        JSONObject jsonObject = JSON.parseObject(eventMessage.getContent());
        if(eventMessage.getBizType().equalsIgnoreCase(EventMessageType.SHOP_DOCTOR_ACCOUNT_ADD.name())||eventMessage.getBizType().equalsIgnoreCase(EventMessageType.SHOP_DOCTOR_ACCOUNT_UPDATE.name())){
            //创建医师角色的账号
            if(jsonObject.get("id") != null){
                Long bizId = Long.valueOf(jsonObject.get("id").toString());
                String userName = String.valueOf(jsonObject.get("username").toString());
                Integer doctorId = -1;
                if(eventMessage.getBizType().equalsIgnoreCase(EventMessageType.SHOP_DOCTOR_ACCOUNT_ADD.name())){
                    doctorId = Integer.valueOf(jsonObject.get("doctorId").toString());
                }
                String name = String.valueOf(jsonObject.get("name").toString());
                String password = String.valueOf(jsonObject.get("password").toString());
                JSONObject hospital = (JSONObject) jsonObject.get("hospital");
                String hospitalName = "";
                if(hospital != null){
                    hospitalName = String.valueOf(hospital.getString("name"));
                }
                bsyUser = BsyUser.builder().bizId(bizId).doctorId(Long.valueOf(doctorId.toString())).realName(name).userName(userName).password(password).roleType("0").roleName("医师").hospitalName(hospitalName).createTime(DateUtil.nowDateTime()).updateTime(DateUtil.nowDateTime()).build();
            }

        }else if(eventMessage.getBizType() .equalsIgnoreCase(EventMessageType.SHOP_CUSTOM_ACCOUNT_ADD.name())||eventMessage.getBizType() .equalsIgnoreCase(EventMessageType.SHOP_CUSTOM_ACCOUNT_UPDATE.name())){
            //创建患者角色的账号
            if(jsonObject.get("id") != null){
                Long bizId = Long.valueOf(jsonObject.get("id").toString());
                String email = String.valueOf(jsonObject.get("email").toString());
                String name = String.valueOf(jsonObject.get("userName").toString());
                String password = String.valueOf(jsonObject.get("password").toString());
                JSONArray hospitals = (JSONArray) jsonObject.get("hospital");
                JSONObject hospital = (JSONObject) hospitals.get(0);
                String hospitalName = "";
                if(hospital != null){
                    hospitalName = String.valueOf(hospital.getString("name"));
                }
                bsyUser = BsyUser.builder().bizId(bizId).doctorId(null).realName(name).userName(email).password(password).roleType("1").roleName("患者").hospitalName(hospitalName).createTime(DateUtil.nowDateTime()).updateTime(DateUtil.nowDateTime()).build();
            }
        }
        return bsyUser;
    }

}
